#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <sys/time.h>
 
#include "data_type.h"
#include "alloc.h"
#include "memfunc.h"
#include "basefunc.h"
#include "struct_deal.h"
#include "crypto_func.h"
#include "memdb.h"
#include "message.h"
#include "ex_module.h"
#include "sys_func.h"
#include "file_struct.h"
#include "login_client.h"
#include "login_test.h"

int state=0; // 0 start
             // 1 register
             // 2 login
             // 3 send key
             // 4 send file
             // 5 log out
char Buf[DIGEST_SIZE*8];

// add para lib_include
int login_client_init(void * sub_proc, void * para)
{
	int ret;
	// add yorself's module init func here
	return 0;
}
int login_client_start(void * sub_proc, void * para)
{
	int ret;
	void * recv_msg;
	int type;
	int subtype;
	// add yorself's module exec func here

	proc_client_outputmsg(sub_proc,"input data: user passwd");

	while(1)
	{
		usleep(time_val.tv_usec);
		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg==NULL)
			continue;
		type=message_get_type(recv_msg);
		subtype=message_get_subtype(recv_msg);
		if(!memdb_find_recordtype(type,subtype))
		{
			printf("message format (%d %d) is not registered!\n",
			message_get_type(recv_msg),message_get_subtype(recv_msg));
			continue;
		}
		if((type==TYPE(LOGIN_TEST))&&(subtype==SUBTYPE(LOGIN)))
		{
			ret=proc_send_login(sub_proc,recv_msg);
		}
	}
	return 0;
}

int proc_send_login(void * sub_proc, void * recv_msg)
{
	int ret;
	RECORD(LOGIN_TEST,LOGIN) login_info;
	void * new_msg;
	int offset;
	int totallen;
		
	ret = message_get_record(recv_msg,&input_msg,0);
	if(ret<0)
		return ret;
	totallen=Strlen(input_msg->message);	
	ret = Getfiledfromstr(Buf,input_msg->message,' ',DIGEST_SIZE*8);
	if(ret<=0)
		return -EINVAL;
	offset=ret;
	login_info.user_name=dup_str(Buf,0);
	ret=Getfiledfromstr(Buf,input_msg->message+offset,' ',DIGEST_SIZE*8);
	offset+=ret;
	if(ret<=0)
		return -EINVAL;	
	Strncpy(login_info.authdata,Buf,DIGEST_SIZE);

	new_msg=message_create(TYPE_PAIR(LOGIN_TEST,LOGIN),NULL);	
	if(new_msg==NULL)
		return -EINVAL;
	ret=message_add_record(new_msg,&login_info);
	if(ret<0)
		return ret;
	
	ret=ex_module_sendmsg(sub_proc,new_msg);

	return ret;
}
